from django.shortcuts import render
from django import http
from django.views import View
from pymysql import DatabaseError

from ranks.models import RankModel


# Create your views here.
class RankView(View):
    """上传分数"""

    def get(self, request, name, score):
        """

        :param request:
        :param name: 用户
        :param score: 分数
        :return:
        """
        # 获取数据库中该用户名对应的个数
        count = RankModel.objects.filter(number=name).count()
        if (count == 0):  # 保存数据
            try:
                newrank = RankModel(number=name, score=score)
                newrank.save()
            except DatabaseError:
                # 如果出错, 返回400
                return http.HttpResponse(status=400)
        else:  # 更新数据
            try:
                newrank = RankModel.objects.get(number=name)
                newrank.score = score
                newrank.save()
            except DatabaseError:
                # 如果出错, 返回400
                return http.HttpResponse(status=400)

        # 拼接参数, 返回:
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'OK',
                                  })


class GEtRankView(View):
    """查询排行"""

    def get(self, request, name):
        """

        :param request:
        :param name: 用户
        :param score: 分数
        :return:
        """
        # 获取排行
        try:
            singleNumber = RankModel.objects.get(number=name)
            myResult = RankModel.objects.filter(score__gt=singleNumber.score).count()
            Resukt = RankModel.objects.filter().order_by('-score')[:10]
        except Exception as e:
            # 如果出错, 返回400
            return http.HttpResponse(status=400)
        #组装数据
        mydict = []
        rank = 1
        for i in Resukt:
            tmpdict = {
                'RankNub': rank,
                'Name': i.number,
                'Score': i.score
            }
            mydict.append(tmpdict)
            rank = rank + 1
        tmpdict = {
            'RankNub': myResult+1,
            'Name': singleNumber.number,
            'Score': singleNumber.score
        }
        mydict.append(tmpdict)
        # 拼接参数, 返回:
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'OK',
                                  'rank': mydict,
                                  },json_dumps_params={'ensure_ascii':False})
